<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_unilevel($in_date){
/*
This function calculate the unilevel bonus for all the sales that is of second sale and onwards for a member (first sale of a member the
commission is calculated using different calculation methods). It will credit to the upline of the purchase owner up to 7 levels, according
to the qualification of an upline in the unilevel.
*/

	//globalize access to unilevel, min_maintain
	global $vars;
	$db=$vars["db"];
	$unilevel = $vars['unilevel'];
	$min_maintain = $vars['min_maintain'];
	//calc_date = get the start and end of the input in_date
	$year=date("Y", strtotime($in_date));
	$month=date("n", strtotime($in_date));
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $month, 1, $year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $month+1, 0, $year));
	//max_level = get the maximum level of unilevel (7)
	$max_level = count($unilevel);
	
	//sales = get all the sales that is confirmed and is not first sale of a member within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->purchase where first_sale!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
	
	//foreach sales
	for($i=0;$i<$t;$i++){
		$sale = mysql_fetch_assoc($r);
		//uid = sale[uid]
		$uid = $sale['uid'];
		//if not isset upline_tree[uid]
		if (!isset($upline_tree[$uid])){
			//downline_id = uid
			//level = 1
			$downline_id = $uid;
			$level = 1;
			do{
				//if not isset users[downline_id]
				if (!isset($users[$downline_id])){
					//users[downline_id] = get short detail for user id = downline_id
					$users[$downline_id] = get_user_short_detail_by_id($downline_id);
				}
				//upline_id = get the upline id of downline_id
				$upline_id = $users[$downline_id]['matrix_upline'];
				//if upline_id
				if ($upline_id){
					if (!isset($users[$upline_id])){
						$users[$upline_id] = get_user_short_detail_by_id($upline_id);
					}
					if ($users[$upline_id]['primary_acc'] == 'y'){
						//upline_tree[uid][level][id] = upline_id
						$upline_tree[$uid][$level]['id'] = $upline_id;
						//upline_tree[uid][level][volume] = get the personal sale for upline_id within the month of input in_date
						$upline_tree[$uid][$level]['volume'] = calc_personal_sales($upline_id, $calc_date['start'], $calc_date['end']);
						//upline_tree[uid][level][downline] = get the total downline for upline_id
						$upline_tree[$uid][$level]['downline'] = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
						//level += 1
						//downline_id = upline_id
						$level += 1;
					}
					$downline_id = $upline_id;
				}
			}while ($upline_id && $level <= $max_level);
		}
		
		//if exist upline_tree[uid]
		if (is_array($upline_tree[$uid])){
			//foreach upline_tree[uid] as level
			for($j = 1,$t2=count($upline_tree[$uid]);$j<$t2;$j++){
				$level = $j;
				//upline_id = upline_tree[uid][level][id]
				$upline_id = $upline_tree[$uid][$level]['id'];
				//if upline_tree[uid][level][volume] >= min_maintain and upline_tree[uid][level][downline] >= unilevel[level][downline]
				if ($upline_tree[$uid][$level]['volume'] >= $min_maintain && $upline_tree[$uid][$level]['downline'] >= $unilevel[$level]['downline']){
					//comm_percent = unilevel[level][percent]
					//comm_amount = comm_percent * sale[amount]
					$comm_percent = $unilevel[$level]['percent'];
					$comm_amount = round($comm_percent * $sale['total_bv'] / 100, 2);
					//insert the commission into the member_comm table with type = unilevel, uid = upline_id, amount = comm_amount, percent = comm_percent, year, month, datetime
					$sql="insert into $db->member_comm (uid, from_uid, type, cid, amount, level, percent, year, month, status, cdate) values ('$upline_id', '$uid', 'u', '$sale[id]', '$comm_amount', '$level', '$comm_percent', '$year', '$month', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					//if insert fail
						//record the error in the variable insert_error
					$insert_comm_detail="UID: $upline_id Sale ID: $sale[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
					if(!mysql_query($sql)){
						$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_success.=$insert_comm_detail;
					}
					//member_comm[upline_id] += comm_amount
					$member_comm[$upline_id] += $comm_amount;
				}
			}
		}
	}
	
	if($insert_error){
		$insert_errmsg.="Failed Unilevel Commission Calculation:<br />\n<br />\n$insert_error";
		$result["errmsg"] .= $insert_errmsg;
	}else{
		$result["status"] = true;
	}
	
	return $result;
}
?>